import { Dialog, Toast } from 'vant';

// 格式化错误信息
function formatErrorMsg(msg) {
    if (!msg) return msg;
    if (/timeout/.test(msg)) {
        return '网络超时';
    }
    if (/Network Error/.test(msg)) {
        return '网络错误';
    }
    return msg;
}

// 时间格式化
export const dateFormat = (date, fmt) => {
    const o = {
        'M+': date.getMonth() + 1, //月份
        'd+': date.getDate(), //日
        'h+': date.getHours(), //小时
        'm+': date.getMinutes(), //分
        's+': date.getSeconds(), //秒
        'q+': Math.floor((date.getMonth() + 3) / 3), //季度
        S: date.getMilliseconds(), //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp('(' + k + ')').test(fmt))
            fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
    return fmt;
};
//时分秒
export function calTimestamp(dates) {
    let date = new Date(dates * 1000);
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hours = date.getHours();
    const minutes = date.getMinutes();
    const seconds = date.getSeconds();

    let time = `${year}/${formatNumber(month)}/${formatNumber(day)} ${[hours, minutes, seconds]
        .map(formatNumber)
        .join(':')}`;
    return time;
}
const formatNumber = n => {
    n = n.toString();
    return n[1] ? n : '0' + n;
};
export function handleError(err) {
    Dialog.alert({
        title: '提示',
        message: JSON.stringify(formatErrorMsg(err.message) || formatErrorMsg(err)).replaceAll('"', ''),
    });
}
export const formatFullTime = time => {
    const date = new Date(time);
    let m = date.getMonth() + 1;
    let d = date.getDate();
    let h = date.getHours();
    let min = date.getMinutes();
    return `${toZero(m)}-${toZero(d)} ${toZero(h)}:${toZero(min)}`;
};

function toZero(data) {
    return data >= 10 ? data : '0' + data;
}
